package main

import (
	"errors"
	"fmt"
	"project/study-go/http/base/session"

	"github.com/gin-gonic/gin"

	"project/study-go/db"
	"project/study-go/http/base/jwt"
	"project/study-go/http/controller"
	"project/study-go/http/controller/admin"
	"project/study-go/middleware"
)

//注册路由总控
func RegisterRoutes(e *gin.Engine) {
	e.LoadHTMLGlob("./template/*")
	e.Use(middleware.AccessLogger())
	//static
	{
		e.Static("/static","./static")
	}

	//default route group "" (route path)
	{
		defaultGroup := e.Group("")
		controller.RegisterRoutes(defaultGroup)
	}

	//api
	//todo
	{
		api := e.Group("/api")
		admin.RegisterRoutes(api)
	}
}

//服务器开启准备例程
func ReadyForServer() error {
	//数据库连接
	err := db.ConnDB()
	if err != nil {
		return errors.New(fmt.Sprintf("Init database connection fail, %s", err.Error()))
	}

	//中间件组件
	err = MiddlewareBase()
	if err != nil {
		return errors.New(fmt.Sprintf("Init Middileware base fail. %s", err.Error()))
	}

	return nil
}

//服务器关闭清理例程
func CleanUpServer() error {
	err := db.DisConnDB()
	if err != nil {
		return errors.New(fmt.Sprintf("Cleanup Databases Connections error. %s", err.Error()))
	}
	return nil
}

//中间件相关依赖组件
func MiddlewareBase() error {
	var (
		err error
	)
	err = jwt.Init()
	session.Init()
	return err
}
